package com.kedll.library.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangweirong on 14/12/18.
 */
public class MapUtils {

    public static class Pair<K, V> {
        private K key;
        private V value;

        public Pair(K k, V v) {
            key = k;
            value = v;
        }
    }

    public static boolean isNotEmpty(Map map) {
        return !isEmpty(map);
    }

    public static boolean isEmpty(Map map) {
        return map == null || map.size() == 0;
    }

    public static <K, V> Map<K, V> makeSimpleMap(Pair<K, V>... elems) {
        Map<K, V> map = new HashMap<K, V>();
        for (Pair<K, V> e : elems) {
            map.put(e.key, e.value);
        }
        return map;
    }

    public static <K, V> V get(Map<K, V> map, String k) {
        if (map == null)
            return null;
        return map.get(k);
    }

    public static String dump(Map map) {
        return dump(map, true);
    }

    public static String dump(Map map, boolean sort) {
        if (isEmpty(map))
            return "";
        StringBuilder sb = new StringBuilder();
        List<Object> keys = new ArrayList<Object>(map.size());
        for (Object k : map.keySet()) {
            keys.add(k.toString());
        }
        if (sort) {
            Collections.sort(keys, new Comparator<Object>() {
                @Override
                public int compare(Object lhs, Object rhs) {
                    return lhs.toString().compareTo(rhs.toString());
                }
            });
        }
        for (Object k : keys) {
            sb.append(k + ":  " + map.get(k)).append("\r\n");
        }
        return sb.toString();
    }
}
